import 'package:flutter/material.dart';

class GSYTabBarWidget extends StatefulWidget {
  ///底部模式type
  static const int BOTTOM_TAB = 1;

  ///顶部模式type
  static const int TOP_TAB = 2;
  final int type;
  final List<Widget> tabItems;
  final List<Widget> tabViews;

  ///整个背景颜色
  final Color backgroundColor;

  ///tab标签的下划线颜色
  final Color indicatorColor;

  ///标题
  final String title;

  const GSYTabBarWidget(
      {Key? key,
      required this.type,
      required this.tabItems,
      required this.tabViews,
      this.backgroundColor = Colors.deepOrange,
      this.indicatorColor = Colors.white,
      required this.title})
      : super(key: key);

  @override
  _GSYTabBarWidgetState createState() {
    return _GSYTabBarWidgetState(
        type, tabItems, tabViews, backgroundColor, indicatorColor, title);
  }
}

class _GSYTabBarWidgetState extends State<GSYTabBarWidget>
    with SingleTickerProviderStateMixin {
  final int _type;
  final List<Widget> _tabItems;
  final List<Widget> _tabViews;
  final Color _backgroundColor;
  final Color _indicatorColor;
  final String _title;

  _GSYTabBarWidgetState(this._type, this._tabItems, this._tabViews,
      this._backgroundColor, this._indicatorColor, this._title)
      : super();

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    if (_type == GSYTabBarWidget.BOTTOM_TAB) {
      _tabController = TabController(
          length: 3, //需要控制的Tab数量
          vsync: this //动画效果的异步处理
          );
    }
  }

  ///整个页面dispose时，记得把控制器也dispose掉，释放内存
  @override
  void dispose() {
    if (_type == GSYTabBarWidget.BOTTOM_TAB) {
      _tabController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_type == GSYTabBarWidget.TOP_TAB) {
      /// 顶部tabBar
      return DefaultTabController(
          length: 3,
          child: Scaffold(
            appBar: AppBar(
              backgroundColor: _backgroundColor,
              title: Text(_title),
              bottom: TabBar(
                tabs: _tabItems,
                indicatorColor: _indicatorColor,
              ),
            ),
            body: TabBarView(children: _tabViews),
          ));
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: _backgroundColor,
        title: Text(_title),
      ),
      body: TabBarView(
          //TabBarView呈现内容，因此放到Scaffold的body中
          controller: _tabController,
          children: _tabViews),
      bottomNavigationBar: Material(
        //为了适配主题风格，包一层Material实现风格套用
        color: _backgroundColor, //底部导航栏颜色
        child: TabBar(
          controller: _tabController,
          tabs: _tabItems,
          indicatorColor: _indicatorColor, //tab标签的下划线颜色
        ),
      ),
    );
  }
}
